import { MainContent } from '../MainContent'
import { Header } from '../Header'
import './index.css'
import { useSetRecoilState } from 'recoil'
import { userInfoState } from '../../store/userInfo';
import { useCallback, useEffect } from 'react';
import { Route, Routes, Navigate, useNavigate } from 'react-router-dom';
import { LoginComponent } from '../User/Login';
import { RegisterComponent } from '../User/Register';
import { getUserInfo } from '../../api/personal';
import { useStaffIm } from '../../hooks/useStaffIm';
import { useManagerIm } from '../../hooks/useManagerIm';

function App() {
  const setUserInfo = useSetRecoilState(userInfoState);
  const socket = useStaffIm();
  const navigate = useNavigate();
  const managerIm = useManagerIm();

  const initUserData = useCallback(async () => {
    const result = await getUserInfo();
    const { user_info, code } = result.data as any;

    if (code === '403') {
      navigate('/user/login');
    }
    setUserInfo(user_info as any); // 用户登录

    return result;
  }, [localStorage.getItem('token')]);

  useEffect(() => {
    initUserData();
    socket.open();
    managerIm.open();

  }, [initUserData, localStorage.getItem('token')]);

  return (
    <div className="App">

      <Routes>
        <Route path='user/*'>
          <Route path={'login'} element={<LoginComponent />} />
          <Route path={'register'} element={<RegisterComponent />} />
        </Route>

        {!localStorage.getItem('token') ? <> <Route path='/*' element={<Navigate to="user/login" />} ></Route> </> :
          <><Route path='conversation/*' element={<>
            <Header />
            <MainContent />
          </>}>
          </Route>
            <Route path='/' element={<Navigate to="conversation/all" />} ></Route>
          </>
        }

      </Routes>

    </div>
  )
}

export default App
